//
//  CommentViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/8/9.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "CommentViewController.h"
#import "ISRDataHelper.h"
//#import "IATConfigViewController.h"
#import "IATConfig.h"

#import "UIViewController+KNSemiModal.h"

@interface CommentViewController () <UITextViewDelegate>

@end

@implementation CommentViewController{
    UITextView  *_textView;
    NSRange     _range;
}

//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
//{
//    UIViewController * parent = [self.view containingViewController];
//    if ([parent respondsToSelector:@selector(dismissSemiModalView)]) {
//        [parent dismissSemiModalView];
//    }
//}

- (void)viewWillLayoutSubviews {
//    self.view.backgroundColor = kClearColor;
//    self.view.window.backgroundColor = kClearColor;
    self.view.frame = CGRectMake(0, SCREEN_HEIGHT/2, SCREEN_WIDTH, SCREEN_HEIGHT/2);
}


-(void)viewWillAppear:(BOOL)animated
{
//    NSLog(@"%s",__func__);
    
    [super viewWillAppear:animated];
    
    [self initRecognizer];
}



-(void)viewWillDisappear:(BOOL)animated
{
//    NSLog(@"%s",__func__);
    
    if ([IATConfig sharedInstance].haveView == NO) {
        
        [_iFlySpeechRecognizer cancel];
        [_iFlySpeechRecognizer setDelegate:nil];
        [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        [_pcmRecorder stop];
        _pcmRecorder.delegate = nil;
    }
    else
    {
        [_iflyRecognizerView cancel];
        [_iflyRecognizerView setDelegate:nil];
        [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
    }
    
    
    [super viewWillDisappear:animated];
}




#pragma mark - IFlySpeechRecognizerDelegate

/**
 volume callback,range from 0 to 30.
 **/
- (void) onVolumeChanged: (int)volume
{
    
}



/**
 Beginning Of Speech
 **/
- (void) onBeginOfSpeech
{
    NSLog(@"onBeginOfSpeech");
}

/**
 End Of Speech
 **/
- (void) onEndOfSpeech
{
    NSLog(@"onEndOfSpeech");
    
    [_pcmRecorder stop];
}


/**
 recognition session completion, which will be invoked no matter whether it exits error.
 error.errorCode =
 0     success
 other fail
 **/
- (void) onError:(IFlySpeechError *) error
{
    NSLog(@"%s",__func__);
    
    if ([IATConfig sharedInstance].haveView == NO ) {
        
        NSString *text ;
        
        if (self.isCanceled) {
            text = NSLocalizedString(@"T_ISR_Cancel", nil);
            
        } else if (error.errorCode == 0 ) {
            if (_result.length == 0) {
                text = NSLocalizedString(@"T_ISR_NoRlt", nil);
            }else {
                text = NSLocalizedString(@"T_ISR_Succ", nil);
                //empty results
                _result = nil;
            }
        }else {
            text = [NSString stringWithFormat:@"Error：%d %@", error.errorCode,error.errorDesc];
            NSLog(@"%@",text);
        }
        
        
    }else {
        NSLog(@"errorCode:%d",[error errorCode]);
    }
    
}

/**
 result callback of recognition without view
 results：recognition results
 isLast：whether or not this is the last result
 **/
- (void) onResults:(NSArray *) results isLast:(BOOL)isLast
{
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    
    _result =[NSString stringWithFormat:@"%@%@", _textView.text,resultString];
    NSString * resultFromJson =  [ISRDataHelper stringFromJson:resultString];
    _textView.text = [NSString stringWithFormat:@"%@%@", _textView.text,resultFromJson];
    
    if (isLast){
        NSLog(@"ISR Results(json)：%@",  self.result);
    }
    NSLog(@"_result=%@",_result);
    NSLog(@"resultFromJson=%@",resultFromJson);
    NSLog(@"isLast=%d,_textView.text=%@",isLast,_textView.text);
}

/**
 result callback of recognition with view
 resultArray：recognition results
 isLast：whether or not this is the last result
 **/
- (void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast
{
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    
    NSLog(@"range  %lu", (unsigned long)_range.location);
    
    // 如果光标小于，就做处理
    if (_range.location < _textView.text.length) {
        
        NSString *str1 = [_textView.text substringToIndex:_range.location];//截取掉下标5之前的字符串
        NSString *str2 = [_textView.text substringFromIndex:_range.location];//截取掉下标3之后的字符串
        _textView.text = [NSString stringWithFormat:@"%@%@%@", str1, result, str2];
    }
    else
        _textView.text = [NSString stringWithFormat:@"%@%@",_textView.text,result];
}



/**
 callback of canceling recognition
 **/
- (void) onCancel
{
    NSLog(@"Recognition is cancelled");
}

-(void) showPopup
{
//    [_popUpView showText: NSLocalizedString(@"T_ISR_Uping", nil)];
}

#pragma mark - IFlyDataUploaderDelegate

/**
 result callback of uploading contacts or customized words
 **/
- (void) onUploadFinished:(IFlySpeechError *)error
{
    NSLog(@"%d",[error errorCode]);
    
    if ([error errorCode] == 0) {
//        [_popUpView showText: NSLocalizedString(@"T_ISR_UpSucc", nil)];
    }
    else {
//        [_popUpView showText: [NSString stringWithFormat:@"%@:%d", NSLocalizedString(@"T_ISR_UpFail", nil), error.errorCode]];
        
    }
    
}


#pragma mark - Initialization

/**
 initialize recognition conctol and set recognition params
 **/
-(void)initRecognizer
{
    NSLog(@"%s",__func__);
    
    if ([IATConfig sharedInstance].haveView == NO) {
        
        //recognition singleton without view
        if (_iFlySpeechRecognizer == nil) {
            _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
        }
        
        [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        //set recognition domain
        [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        
        _iFlySpeechRecognizer.delegate = self;
        
        if (_iFlySpeechRecognizer != nil) {
            IATConfig *instance = [IATConfig sharedInstance];
            
            //set timeout of recording
            [_iFlySpeechRecognizer setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
            //set VAD timeout of end of speech(EOS)
            [_iFlySpeechRecognizer setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
            //set VAD timeout of beginning of speech(BOS)
            [_iFlySpeechRecognizer setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
            //set network timeout
            [_iFlySpeechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
            
            //set sample rate, 16K as a recommended option
            [_iFlySpeechRecognizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
            
            //set language
            [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            //set accent
            [_iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
            
            //set whether or not to show punctuation in recognition results
            [_iFlySpeechRecognizer setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
            
        }
        
        //Initialize recorder
        if (_pcmRecorder == nil)
        {
            _pcmRecorder = [IFlyPcmRecorder sharedInstance];
        }
        
        _pcmRecorder.delegate = self;
        
        [_pcmRecorder setSample:[IATConfig sharedInstance].sampleRate];
        
        [_pcmRecorder setSaveAudioPath:nil];    //not save the audio file
        
    }else  {
        
        //recognition singleton with view
        if (_iflyRecognizerView == nil) {
            
            _iflyRecognizerView= [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
        }
        
        [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        //set recognition domain
        [_iflyRecognizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        
        
        _iflyRecognizerView.delegate = self;
        
        if (_iflyRecognizerView != nil) {
            IATConfig *instance = [IATConfig sharedInstance];
            //set timeout of recording
            [_iflyRecognizerView setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
            //set VAD timeout of end of speech(EOS)
            [_iflyRecognizerView setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
            //set VAD timeout of beginning of speech(BOS)
            [_iflyRecognizerView setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
            //set network timeout
            [_iflyRecognizerView setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
            
            //set sample rate, 16K as a recommended option
            [_iflyRecognizerView setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
            
            //set language
            [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            //set accent
            [_iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
            //set whether or not to show punctuation in recognition results
            [_iflyRecognizerView setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
            
        }
    }
}




-(void)setExclusiveTouchForButtons:(UIView *)myView
{
    for (UIView * button in [myView subviews]) {
        if([button isKindOfClass:[UIButton class]])
        {
            [((UIButton *)button) setExclusiveTouch:YES];
        }
        else if ([button isKindOfClass:[UIView class]])
        {
            [self setExclusiveTouchForButtons:button];
        }
    }
}


#pragma mark - IFlyPcmRecorderDelegate

- (void) onIFlyRecorderBuffer: (const void *)buffer bufferSize:(int)size
{
    NSData *audioBuffer = [NSData dataWithBytes:buffer length:size];
    
    int ret = [self.iFlySpeechRecognizer writeAudio:audioBuffer];
    if (!ret)
    {
        [self.iFlySpeechRecognizer stopListening];
    }
}

- (void) onIFlyRecorderError:(IFlyPcmRecorder*)recoder theError:(int) error
{
    
}

//range from 0 to 30
- (void) onIFlyRecorderVolumeChanged:(int) power
{
    //    NSLog(@"%s,power=%d",__func__,power);
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self buildUI];
    
}

#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.view.backgroundColor = kWhiteColor;
    
    UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    [self.view addSubview:navView];
    navView.backgroundColor = UIMainColorRGB;
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:cancelBtn];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = kUHSystemFontWithSize(14);
    [cancelBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    cancelBtn.frame = CGRectMake(0, 20, 50, 44);
    [cancelBtn addTarget:self action:@selector(cancelPostClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *commentL = [[UILabel alloc] initWithFrame:CGRectMake(SW(2)-50, 20, 100, 44)];
    [self.view addSubview:commentL];
    commentL.textAlignment = NSTextAlignmentCenter;
    commentL.text = @"发表评论";
    commentL.textColor = kWhiteColor;
    commentL.font = kUHSystemFontWithSize(15);
    
    
    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:sendBtn];
    sendBtn.titleLabel.font = kUHSystemFontWithSize(14);
    
    sendBtn.frame = CGRectMake(SCREEN_WIDTH-50, 20, 50, 44);
    [sendBtn setBackgroundColor:UIMainColorRGB];
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendCommentClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(SW(40), navView.height, SCREEN_WIDTH-SW(20), 100)];
    [self.view addSubview:_textView];
    _textView.text = @"你想说点什么？";
    _textView.textColor = kLightGrayColor;
    _textView.delegate = self;
//    _textView.textColor = kGrayColor;
//    [_textView becomeFirstResponder];
    if (self.atName.length > 0) {
//        _textView.text = [NSString stringWithFormat:@"@%@:你想说点什么？", self.atName];
        _textView.text = [NSString stringWithFormat:@"@%@", self.atName];
        // 不同颜色
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:_textView.text];
        NSRange redRange = NSMakeRange([[string string] rangeOfString:[NSString stringWithFormat:@"@%@", self.atName]].location, [[string string] rangeOfString:[NSString stringWithFormat:@"@%@", self.atName]].length);
        [string addAttribute:NSForegroundColorAttributeName value:RGB(70, 102, 165) range:redRange];
        [_textView setAttributedText:string];
    }
    _textView.font = kUHSystemFontWithSize(15);
    
    
    UIButton *yuyinBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:yuyinBtn];
    yuyinBtn.titleLabel.font = kUHSystemFontWithSize(14);
    yuyinBtn.frame = CGRectMake(SCREEN_WIDTH-100, _textView.y+_textView.height, 80, 44);
    [yuyinBtn setBackgroundColor:UIMainColorRGB];
    yuyinBtn.titleLabel.font = kUHSystemFontWithSize(14);
    [yuyinBtn setTitle:@"语音输入" forState:UIControlStateNormal];
    [yuyinBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [yuyinBtn addTarget:self action:@selector(voiceClick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)voiceClick:(UIButton *)btn {
    
    [IATConfig sharedInstance].haveView = YES;
    
    if ([IATConfig sharedInstance].haveView == NO) {
        
//        [_textView setText:@""];
        
        
        if ([_textView.text isEqualToString:@"你想说点什么？"]) {
            _textView.text =@"";
            _textView.textColor = kBlackColor;
        }

        
        [_textView resignFirstResponder];
        self.isCanceled = NO;
        self.isStreamRec = NO;
        
        if(_iFlySpeechRecognizer == nil)
        {
            [self initRecognizer];
        }
        
        [_iFlySpeechRecognizer cancel];
        
        //Set microphone as audio source
        [_iFlySpeechRecognizer setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
        
        //Set result type
        [_iFlySpeechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];
        
        //Set the audio name of saved recording file while is generated in the local storage path of SDK,by default in library/cache.
        [_iFlySpeechRecognizer setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        
        [_iFlySpeechRecognizer setDelegate:self];
        
        BOOL ret = [_iFlySpeechRecognizer startListening];
        
        if (ret) {
            
        }else{
//            [_popUpView showText: NSLocalizedString(@"M_ISR_Fail", nil)];//Last session may be not over, recognition not supports concurrent multiplexing.
        }
    }else {
        
        if(_iflyRecognizerView == nil)
        {
            [self initRecognizer ];
        }
        
//        [_textView setText:@""];
        if ([_textView.text isEqualToString:@"你想说点什么？"]) {
            _textView.text =@"";
            _textView.textColor = kBlackColor;
        }
        
        [_textView resignFirstResponder];
        
        //Set microphone as audio source
        [_iflyRecognizerView setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
        
        //Set result type
        [_iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
        
        //Set the audio name of saved recording file while is generated in the local storage path of SDK,by default in library/cache.
        [_iflyRecognizerView setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        
        BOOL ret = [_iflyRecognizerView start];
        if (ret) {
        }
    }
    
    
}

#pragma mark ===========响应方法==========
// 取消发布
- (void)cancelPostClick:(UIButton *)sender {
//    [self dismissViewControllerAnimated:YES completion:nil];
    UIViewController * parent = [self.view containingViewController];
    if ([parent respondsToSelector:@selector(dismissSemiModalView)]) {
        [parent dismissSemiModalView];
    }

}
// 发布评论
- (void)sendCommentClick:(UIButton *)sender {
    
    if ([_textView.text isEqualToString:@"你想说点什么？"] || [_textView.text isEqualToString:@""]) {
        [self presentViewController:[LZCTools alertMessage:@"内容不可以为空"] animated:YES completion:nil];
        return;
    }
    
    NSString *url = [NSString stringWithFormat:@"%@/%@/replies", APIPosts, self.postId];
    NSDictionary *param = @{@"contents":_textView.text, @"pid":self.pid};
    // 2 是文章
    if (self.type == 2) {
        url = [NSString stringWithFormat:@"%@/%@/comments", APIArticles, self.postId];
        param = @{@"content":_textView.text, @"pid":self.pid};
    }
    
    else if (self.type == 3) {
        url = [NSString stringWithFormat:@"%@/%@/comments", APIQuestionsAnswers, self.postId];
        param = @{@"body":_textView.text};
    }
    
    [[NetworkTool sharedTool] requestWithName:@"评论" URLString:url parameters:param method:@"POST" callBack:^(id responseObject) {
//        [self dismissViewControllerAnimated:YES completion:nil];
        UIViewController * parent = [self.view containingViewController];
        if ([parent respondsToSelector:@selector(dismissSemiModalView)]) {
            [parent dismissSemiModalView];
        }
        
        //创建通知
        NSNotification *notification =[NSNotification notificationWithName:@"postComment" object:nil userInfo:nil];
        //通过通知中心发送通知
        [[NSNotificationCenter defaultCenter] postNotification:notification];

    }];
    
}


#pragma mark ===========代理方法==========
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
//    if ([text isEqualToString:@"\n"]) {
//        [textView resignFirstResponder];
//        return NO;
//    }
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {

    if ([textView.text isEqualToString:@"你想说点什么？"]) {
        textView.text =@"";
        textView.textColor = kBlackColor;
    }
    
    
    return YES;
}

- (void)textViewDidChangeSelection:(UITextView *)textView {
    
    _range = textView.selectedRange;
    NSLog(@"range  %lu", (unsigned long)_range.length);
    NSLog(@"range  %lu", (unsigned long)_range.location);
}


//- (void)textViewDidChange:(UITextView *)textView
//{
//        NSRange  reservedRange = textView.selectedRange;
//    textView.selectedRange = NSMakeRange(textView.text.length, 0);
//    CGPoint cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.start].origin;
//        NSLog(@"range ===%f,%f",cursorPosition.y,cursorPosition.x);
//        textView.selectedRange = reservedRange;
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
